package 实验三.三层cs;

import java.util.*;
  
public class DataServer {  
    private static List<Contact> contacts = new ArrayList<>();  
    private static Map<String, Integer> contactIndex = new HashMap<>();  
  
    // 私有构造函数，防止实例化  
    private DataServer() {}  
  
    public static void addContact(Contact contact) {  
        if (contactIndex.containsKey(contact.name)) {  
            System.out.println("该联系人已存在（数据服务器）");  
        } else {  
            contacts.add(contact);  
            contactIndex.put(contact.name, contacts.size() - 1);  
            System.out.println("联系人添加成功（数据服务器）");  
        }  
    }  
  
    public static String modifyContact(String name, String address, String phone) {  
        if (contactIndex.containsKey(name)) {  
            contacts.get(contactIndex.get(name)).address = address;  
            contacts.get(contactIndex.get(name)).phone = phone;  
            System.out.println("联系人修改成功（数据服务器）");  
            return contacts.get(contactIndex.get(name)).toString();  
        } else {  
            System.out.println("联系人不存在（数据服务器）");  
        }  
        return "联系人不存在（数据服务器）";  
    }  
  
    public static void deleteContact(String name) {  
        if (contactIndex.containsKey(name)) {  
            contacts.remove(contactIndex.get(name));  
            contactIndex.remove(name);  
            System.out.println("联系人删除成功（数据服务器）");  
        } else {  
            System.out.println("联系人不存在（数据服务器）");  
        }  
    }  
  
    public static String viewContact() {  
        StringBuilder result = new StringBuilder();  
        for (Contact contact : contacts) {  
            result.append(contact).append("\n");  
        }  
        return result.toString();  
    }  
}